import http from '@/common/http';
import { Dialog } from 'mand-mobile';
import {
  GET_RECOMMAND_ROUTES,
  GET_START_CITYS,
  GET_END_CITYS
} from './actions.types';
import {
  SET_START_CITY_OBJ,
  SET_END_CITY_OBJ,
  SET_START_CITY_LIST,
  SET_END_CITY_LIST,
  GET_RECOMMAND_ROUTES_SUCCESS,
  EXCHANGE_START_END,
  CONFIRM_ROUTE
} from './mutations.types';
import Loading from '@/components/loading';
function pySegSort(arr, isStart) {
  if (!String.prototype.localeCompare) return null;

  var letters = '*ABCDEFGHJKLMNOPQRSTWXYZ'.split('');
  var zh = '阿吧嚓哒妸发旮哈讥咔垃妈拏噢妑七呥扨它穵夕丫帀'.split('');

  var segs = [];
  var curr;
  letters.forEach(function(item, i) {
    curr = {
      letter: item,
      data: []
    };
    arr.forEach(function(obj) {
      obj.type = '1';
      let item2 = isStart ? obj.start_route : obj.end_route;
      let p = pinyinUtil.getFirstLetter(item2[0]);
      if (item === p) {
        curr.data.push(obj);
      }
      // if (
      //     (!zh[i - 1] || zh[i - 1].localeCompare(item2, 'zh-Hans-CN', { sensitivity: 'accent' }) <= 0) &&
      //     item2.localeCompare(zh[i], 'zh-Hans-CN', { sensitivity: 'accent' }) === -1
      // ) {
      //     curr.data.push(obj);
      // }
    });
    if (curr.data.length) {
      segs.push(curr);
      // curr.data.sort(function (a, b) {
      //     let x = isStart ? a.start_route : a.end_route
      //     let y = isStart ? b.start_route : b.end_route
      //     return x.localeCompare(y);
      // });
    }
  });
  return segs;
}
function airStationSort(arr) {
  var letters = '*ABCDEFGHJKLMNOPQRSTWXYZ'.split('');
  var segs = [];
  var curr;
  letters.forEach(function(item, i) {
    curr = {
      letter: item,
      data: []
    };
    arr.forEach(function(obj) {
      let p = pinyinUtil.getFirstLetter(obj.stationName)[0];
      if (item === p) {
        curr.data.push(obj);
      }
    });
    if (curr.data.length) {
      segs.push(curr);
    }
  });
  return segs;
}
const defaultState = () => {
  return {
    startCityObj: null,
    endCityObj: null,
    startCityList: [],
    sortedStartCityList: [],
    endCityList: [],
    sortedEndCityList: [],
    recommandRouteList: [],
    selectedRoute: null,
    confirmdRoute: null,
    hotCitys: [],
    startAirStations: [],
    sortedStartAirStations: [],
    endAirStations: [],
    sortedEndAirStations: []
  };
};
const state = defaultState();
const getters = {
  getAllCitys(state) {
    return state.citys.citys;
  },
  getStartCityList(state) {
    return state.startCityList;
  },
  getEndCityList(state) {
    return state.endCityList;
  },
  getRecommandRouteList(state) {
    return state.recommandRouteList;
  },
  getStartCityObj(state) {
    return state.startCityObj;
  },
  getEndCityObj(state) {
    return state.endCityObj;
  },
  getSortedStartCity(state) {
    return state.sortedStartCityList;
  },
  getSortedEndCity(state) {
    return state.sortedEndCityList;
  },
  getConfirmdRoute(state) {
    if (state.confirmdRoute) {
      return state.confirmdRoute;
    } else {
      let city = localStorage.getItem('CONFIRMED_CITY');
      if (city) {
        return JSON.parse(city);
      } else {
        return null;
      }
    }
  },
  hotCitys(state) {
    return state.hotCitys;
  },
  startAirStations(state) {
    return state.startAirStations;
  },
  sortedStartAirStations(state) {
    return state.sortedStartAirStations;
  },
  sortedEndAirStations(state) {
    return state.sortedEndAirStations;
  },
  endAirStations(state) {
    return state.endAirStations;
  }
};
const actions = {
  [GET_RECOMMAND_ROUTES](context, params) {
    let data = {};
    Object.assign(data, params); // 复制操作，防止操作原数据
    return new Promise((resolve, reject) => {
      Loading.show();
      http.post('/pakj/route/getCommonlyRoute', params).then(res => {
        Loading.hide();
        if (res.data.code === '000000') {
          context.commit(GET_RECOMMAND_ROUTES_SUCCESS, res.data.data);
          resolve();
        } else {
          Dialog.alert({
            title: '错误',
            content: res.data.msg,
            confirmText: '确定'
          });
          reject(new Error(res.data.code + ':' + res.data.msg));
        }
      });
    });
  },
  [GET_START_CITYS](context) {
    return new Promise((resolve, reject) => {
      Loading.show();
      http.post('pakj/route/getNewStartCitys').then(res => {
        Loading.hide();
        if (res.data.code === '000000') {
          context.commit(SET_START_CITY_LIST, res.data.data);
          resolve();
        } else {
          Dialog.alert({
            title: '错误',
            content: res.data.msg,
            confirmText: '确定'
          });
          reject(new Error(res.data.code + ':' + res.data.msg));
        }
      });
    });
  },
  [GET_END_CITYS](context) {
    return new Promise((resolve, reject) => {
      Loading.show();
      let startCityObj = context.getters.getStartCityObj;
      let startCity = '';
      if (startCityObj && startCityObj.type === '1') {
        startCity = startCityObj.start_route;
      } else if (startCityObj && startCityObj.type === '2') {
        startCity = startCityObj.start_auto_name;
      } else {
        Loading.hide();
        reject(new Error('无法获取终点列表'));
      }
      let params = {
        start_city: startCity
      };
      http.post('pakj/route/getNewEndCitys', params).then(res => {
        Loading.hide();
        if (res.data.code === '000000') {
          context.commit(SET_END_CITY_LIST, res.data.data);
          resolve(true);
        } else {
          Dialog.alert({
            title: '错误',
            content: res.data.msg,
            confirmText: '确定'
          });
          reject(new Error(res.data.code + ':' + res.data.msg));
        }
      });
    });
  },
  getHotCitys(context) {
    return new Promise((resolve, reject) => {
      Loading.show();
      http.post('pakj/route/getHotCity').then(res => {
        Loading.hide();
        if (res.data.code === '000000') {
          context.commit('setHotCitys', res.data.data);
          resolve();
        } else {
          Dialog.alert({
            title: '错误',
            content: res.data.msg,
            confirmText: '确定'
          });
          reject(new Error(res.data.code + ':' + res.data.msg));
        }
      });
    });
  },
  getStartAirStations(context, cityName) {
    return new Promise((resolve, reject) => {
      Loading.show();
      let params = {
        name: cityName
      };
      http.post('pakj/route/getAirStation', params).then(res => {
        Loading.hide();
        if (res.data.code === '000000') {
          context.commit('setStartAirStations', res.data.data);
          resolve();
        } else {
          Dialog.alert({
            title: '错误',
            content: res.data.msg,
            confirmText: '确定'
          });
          reject(new Error(res.data.code + ':' + res.data.msg));
        }
      });
    });
  },
  getEndAirStations(context) {
    return new Promise((resolve, reject) => {
      Loading.show();
      let startCityObj = context.getters.getStartCityObj;
      let stationName = '';
      let stationId = '';
      if (startCityObj && startCityObj.type === '1') {
        stationName = startCityObj.start_route;
      } else if (startCityObj && startCityObj.type === '2') {
        stationName = startCityObj.start_auto_name;
      } else {
        Loading.hide();
        reject(new Error('无法获取终点列表'));
      }
      let params = {
        name: stationName
      };
      http.post('pakj/route/getAirStation', params).then(res => {
        Loading.hide();
        if (res.data.code === '000000') {
          context.commit('setEndAirStations', res.data.data);
          resolve();
        } else {
          Dialog.alert({
            title: '错误',
            content: res.data.msg,
            confirmText: '确定'
          });
          reject(new Error(res.data.code + ':' + res.data.msg));
        }
      });
    });
  }
};
const mutations = {
  resetCityStore(state) {
    console.log('---------重置城市信息---------');
    Object.assign(state, defaultState());
  },
  [GET_RECOMMAND_ROUTES_SUCCESS](state, data) {
    state.recommandRouteList = data;
  },
  [SET_START_CITY_LIST](state, citys) {
    state.startCityList = citys;
    state.sortedStartCityList = pySegSort(citys, true);
  },
  [SET_END_CITY_LIST](state, citys) {
    state.endCityList = citys;
    state.sortedEndCityList = pySegSort(citys, false);
  },
  [SET_START_CITY_OBJ](state, cityObj) {
    state.startCityObj = cityObj;
    if (state.endCityObj) {
      state.endCityObj = null;
    }
  },
  [SET_END_CITY_OBJ](state, cityObj) {
    state.endCityObj = cityObj;
  },
  [EXCHANGE_START_END](state) {
    console.log('交换城市');
    let oldStart = JSON.parse(JSON.stringify(state.startCityObj));
    let oldEnd = JSON.parse(JSON.stringify(state.endCityObj));
    state.startCityObj = oldEnd;
    state.endCityObj = oldStart;
    Object.assign(state.startCityObj, {
      start_route: oldEnd.end_route,
      end_route: oldEnd.start_route,
      route_id: oldEnd.route_id,
      back_route_id: oldEnd.back_route_id
    });
    Object.assign(state.endCityObj, {
      start_route: oldEnd.start_route,
      end_route: oldEnd.end_route,
      route_id: oldEnd.back_route_id,
      back_route_id: oldEnd.route_id
    });
  },
  [CONFIRM_ROUTE](state, city) {
    state.confirmdRoute = city;
    localStorage.setItem('CONFIRMED_CITY', JSON.stringify(city));
  },
  setHotCitys(state, citys) {
    state.hotCitys = citys;
  },
  setStartAirStations(state, stations) {
    state.startAirStations = stations;
    state.sortedStartAirStations = airStationSort(stations);
  },
  setEndAirStations(state, stations) {
    state.endAirStations = stations;
    state.sortedEndAirStations = airStationSort(stations);
  }
};
export default {
  state,
  getters,
  actions,
  mutations
};
